﻿//-----------------------------------------------------------------------
// <copyright file="ConversationFactory.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace Microsoft.Live.Messenger
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;

    internal sealed class ConversationFactory
    {
        private readonly List<Conversation> pendingConversations = new List<Conversation>();

        private readonly Dictionary<MessengerEntity, Conversation> conversations = new Dictionary<MessengerEntity, Conversation>();

        private readonly User user;

        public ConversationFactory(User user)
        {
            this.user = user;
        }

        public Conversation FindOrCreate(object obj)
        {
            if (obj == null)
            {
                return null;
            }

            return FindOrCreate(new MessengerEntity(obj));
        }

        public Conversation FindOrCreate(MessengerEntity entity)
        {
            Conversation conversation = null;

            if (this.pendingConversations.Count > 0)
            {
                Debug.Assert(this.pendingConversations.Count == 1);

                conversation = this.pendingConversations[0];
                this.pendingConversations.RemoveAt(0);
                return conversation;
            }

            if (this.conversations.TryGetValue(entity, out conversation))
            {
                return conversation;
            }

            conversation = new Conversation(entity, this.user);

            this.conversations.Add(entity, conversation);

            return conversation;
        }

        public void Add(Conversation conversation)
        {
            Conversation existing = null;

            if (conversation.Entity == null)
            {
                this.pendingConversations.Add(conversation);
            }
            else
            {
                if (!this.conversations.TryGetValue(conversation.Entity, out existing))
                {
                    this.conversations.Add(conversation.Entity, conversation);
                }
            }
        }
    }
}